package top.yuzt.noticeserver.controller;


import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.yuzt.noticeserver.entity.Groupmembers;
import top.yuzt.noticeserver.entity.PackUserRole;
import top.yuzt.noticeserver.entity.Users;
import top.yuzt.noticeserver.mapper.GroupmembersMapper;
import top.yuzt.noticeserver.mapper.UsersMapper;
import top.yuzt.noticeserver.service.impl.UsersServiceImpl;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yuzt
 * @since 2024-05-03
 */
@RestController
@RequestMapping("/users")
public class UsersController {
    @Autowired
     UsersServiceImpl usersService = new UsersServiceImpl();

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private GroupmembersMapper groupmembersMapper;


    @PostMapping("/reg")
    public Boolean register(@RequestBody Users users){

            return usersService.saveOrUpdate(users);
    }
    @GetMapping("/find")
    public Users find(Integer id){
        return usersService.getById(id);
    }

    @GetMapping("/finduser")
    public Users finduser(String username){
        return usersMapper.findByUsername(username);
    }

    @PostMapping("/login")
    public SaResult login(@RequestBody Users users){
        Users dbuser = usersMapper.findByUsername(users.getUsername());
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        if(dbuser != null){
            if(dbuser.getUsername().equals(users.getUsername()) && dbuser.getPassword().equals(users.getPassword())) {
                StpUtil.login(10001);
                tokenInfo = StpUtil.getTokenInfo();
            }
        }
        return SaResult.data(tokenInfo).set("user",dbuser);
    }
    //根据组id查询成员id
    @GetMapping("/groupmembers")
    public List<PackUserRole> gettGroupmembers(String id){
        List<PackUserRole> usergroupsList = new ArrayList<>();
        List<Groupmembers> groupmembersList = groupmembersMapper.findUserByGroupid(id);
        Collections.sort(groupmembersList, new Comparator<Groupmembers>() {
            @Override
            public int compare(Groupmembers o1, Groupmembers o2) {
                return Integer.compare(o2.getRole(), o1.getRole()); // 从大到小排序
            }
        });
        for(Groupmembers x : groupmembersList){
            Users user = usersMapper.findByUserID(x.getUserid());
            int role = x.getRole();
            PackUserRole pack = new PackUserRole(user, role);
            usergroupsList.add(pack);
        }
        return usergroupsList;
    }
}
